<script setup lang="ts">
import { ref } from 'vue';
import type { UploadFile, UploadProps } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { updateCourseCoverApi } from '@/api/MicroScene/MicroSceneApi';

const props = defineProps<{
  open: boolean;
  currentCoverUrl: string;
  courseId: number;
  areaId: number;
}>();

const emit = defineEmits<{
  (e: 'changeOpenState', openState: boolean): void;
  (e: 'success'): void;
}>();

const imageUrl = ref<string>(props.currentCoverUrl);
const fileList = ref<UploadFile[]>([]);

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  // 检查文件类型
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片！');
    return false;
  }

  // 检查文件大小
  const isLt2M = file?.size ? file.size / 1024 / 1024 < 2 : false;
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB！');
    return false;
  }

  // 更新文件列表
  fileList.value = [file];

  // 创建本地预览
  const reader = new FileReader();
  reader.addEventListener('load', () => {
    imageUrl.value = reader.result as string;
  });
  reader.readAsDataURL(file);

  return false;
};

const handleOk = async () => {
  try {
    if (!fileList.value[0]) {
      message.error('请选择要上传的图片');
      return;
    }

    await updateCourseCoverApi(
      props.courseId,
      props.areaId,
      fileList.value[0].originFileObj as File,
    );

    message.success('封面更新成功');
    emit('changeOpenState', false);
    emit('success');
  }
  catch (error: any) {
    message.error(`更新失败：${error.message}`);
  }
};

const handleCancel = () => {
  imageUrl.value = props.currentCoverUrl;
  fileList.value = [];
  emit('changeOpenState', false);
};
</script>

<template>
  <a-modal
    :open="open"
    title="修改课程封面"
    :mask-closable="false"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div style="display: flex; justify-content: center; align-items: center;">
      <a-upload
        v-model:file-list="fileList"
        list-type="picture-card"
        :show-upload-list="false"
        :before-upload="beforeUpload"
        :multiple="false"
        :max-count="1"
      >
        <img
          v-if="imageUrl"
          :src="imageUrl"
          alt="封面"
          style="width: 95%; height: 95%; object-fit: cover;"
        >
        <div v-else>
          <UploadOutlined />
          <div style="margin-top: 0.5rem;">
            上传封面图
          </div>
        </div>
      </a-upload>
    </div>
  </a-modal>
</template>

<style scoped>
</style>
